package com.lancoo.cvas.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lancoo.cvas.entity.*;
import com.lancoo.cvas.mapper.ClassInfoMapper;
import com.lancoo.cvas.mapper.RoomMapper;
import com.lancoo.cvas.mapper.TeachingClassMapper;
import com.lancoo.cvas.pojo.common.Deleted;
import com.lancoo.cvas.pojo.common.ScheduleState;
import com.lancoo.cvas.pojo.vo.Campus;
import com.lancoo.cvas.pojo.vo.ClassInfoByClassResponses;
import com.lancoo.cvas.pojo.vo.ClassTree;
import com.lancoo.cvas.pojo.vo.TeachingClassCourseDto;
import com.lancoo.cvas.service.BasicRuleService;
import com.lancoo.cvas.service.ClassInfoService;
import com.lancoo.cvas.service.ScheduleService;
import com.lancoo.cvas.service.YunService;
import com.lancoo.cvas.util.BatchInsert;
import io.reactivex.rxjava3.internal.operators.observable.ObservableJust;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;


@Service("classInfoService")
public class ClassInfoServiceImpl extends ServiceImpl<ClassInfoMapper, ClassInfo> implements ClassInfoService {

    @Resource
    private RoomMapper roomMapper;

    @Resource
    private ClassInfoMapper classInfoMapper;

    @Resource
    @Lazy
    private YunService yunService;
    @Resource
    private TeachingClassMapper teachingClassMapper;
    @Resource
    private ScheduleService scheduleService;

    @Resource
    private BasicRuleService basicRuleService;


    @Override
    public void syncClassInfo(Integer taskId, String schoolId, Set<ClassInfo> classInfos, String term) {
        //填充默认校区
        List<Campus> campusList = roomMapper.getCampusList(schoolId, term);
        if (CollUtil.isNotEmpty(campusList)) {
            Campus campus = campusList.get(0);
            classInfos.forEach(o -> {
                o.setCampusId(campus.getCampusId());
                o.setCampusName(campus.getCampusName());
            });
        }




        if (CollUtil.isNotEmpty(classInfos)) {
//            this.saveBatch(classInfos);

            Consumer<List<ClassInfo>> consumer = o -> classInfoMapper.addBatch(o);
            BatchInsert.batchSplitInsert(new ArrayList<>(classInfos), consumer);

        }

    }

    @Override
    public List<ClassTree> getClassTree(Integer taskId,Integer module) {
        List<ClassInfo> classInfoList = this.lambdaQuery().eq(ClassInfo::getTaskId, taskId).list();
        Page<TeachingClassCourseDto> page = new Page<>(1, -1);
        List<TeachingClassCourseDto> records = teachingClassMapper.getCourseTeachingClassForArrange(page, taskId, null, null, null, null).getRecords();


        if(module == 1){
            List<String> classIds = records.stream().filter(o -> StrUtil.isNotEmpty(o.getClassId())
                    && StrUtil.isEmpty(o.getUniqueShiftSign())
            ).map(TeachingClassCourseDto::getClassId).distinct().collect(Collectors.toList());
            classInfoList = classInfoList.stream().filter(o -> classIds.contains(String.valueOf(o.getId())))
                    .collect(Collectors.toList());
        }

        if (module == 2){
            Map<Long, List<ClassInfo>> classMap = classInfoList.stream().collect(Collectors.groupingBy(ClassInfo::getId));
//            Page<TeachingClassCourseDto> page = new Page<>(1, -1);
//            List<TeachingClassCourseDto> records = teachingClassMapper.getCourseTeachingClassForArrange(page, taskId, null, null, null, null).getRecords();

            records = records.stream().filter(o -> StrUtil.isNotEmpty(o.getClassId())
                    //合班的话  不会再行政班那边显示
//                    && ((o.getSubId() == null && StrUtil.isEmpty(o.getUniqueShiftSign()))  || (o.getSubId() != null &&o.getSubId() == 1))
            ).collect(Collectors.toList());
            for (TeachingClassCourseDto record : records) {
                if (record.getState() == ScheduleState.CONFLICT.getCode()
                        || record.getState() == ScheduleState.UNARRANGE.getCode()){
                    for (String s : record.getClassId().split(",")) {
                            classMap.get(Long.valueOf(s)).get(0).setScheduleState(false);

                    }
                }
            }
            classInfoList.clear();
            classMap.values().forEach(classInfoList::addAll);

            HashSet<Long> ids = new HashSet<>();
            List<Long> teachingClassIds = scheduleService.lambdaQuery().eq(Schedule::getTaskId, taskId)
                    .eq(Schedule::getDeleted, Deleted.NOT.getCode())
                    .list().stream().map(Schedule::getTeachingClassId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(teachingClassIds)){
                List<TeachingClass> teachingClasses = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()
                                .in(TeachingClass::getTeachingClassId, teachingClassIds)
                                .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()))
                        .stream().filter(o -> StrUtil.isNotEmpty(o.getClassId())
//                                && ((o.getSubId() == null && StrUtil.isEmpty(o.getUniqueShiftSign()))  || (o.getSubId() != null &&o.getSubId() == 1))
                        ).collect(Collectors.toList());
                for (TeachingClass teachingClass : teachingClasses) {
                    String classId = teachingClass.getClassId();
                    if (StrUtil.isNotEmpty(classId)){
                        for (String s : classId.split(",")) {
                            ids.add(Long.valueOf(s));
                        }
                    }
                }
            }else {
                classInfoList = new ArrayList<>();
            }

            classInfoList = classInfoList.stream().filter(o -> ids.contains(o.getId())).collect(Collectors.toList());
        }
        return ClassInfo.toTree(classInfoList);
    }

    @Override
    public List<ClassInfo> getUnSetClassInfo(Integer taskId) {

        //获取未设置教室班级
        List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId,taskId));

        ClassInfoByClassResponses classInfoByClass = basicRuleService.getClassInfoByClass(taskId,  null, null, 1, 1000);

        List<ClassInfo> collect = classInfoList.stream().filter(p -> classInfoByClass.getFacultyClassInfoList().stream().anyMatch(o -> o.getClassId().equals(p.getClassId()))).collect(Collectors.toList());


        return collect.stream().filter(p-> ObjUtil.isNull(p.getRoomId())).collect(Collectors.toList());
    }


    @Override
    public List<ClassInfo> getAllClass(Integer taskId, String gradeId) {
//        return classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>()
//                .eq(ClassInfo::getTaskId,taskId)
//                .eq(StrUtil.isNotEmpty(gradeId),ClassInfo::getGradeId,gradeId)
//                .orderBy(true,true,ClassInfo::getClassName));
        return classInfoMapper.getAllClass(taskId,gradeId);
    }
}